跟變數一樣 JavaScript 在 ES6 為函式新添加一種寫法,他和傳統函式有以下差異:
除了以上和傳統函式不同,箭頭函式本身一個可以縮寫特性,先來看一下範例:
這是原本傳統函式:
const sayHi = function(name){
	return `Hello ${name}` 
}
console.log(sayHi('Ryder')) //Hello Ryder
如果是使用 箭頭函式 可以省略 return 以及 { }
const sayHi = (name)=> `Hello ${name}` 
console.log(sayHi('Ryder')) //Hello Ryder
當參數只有一個時,也可以將包著參數的 ()  給省略。
const sayHi = name => `Hello ${name}` 
console.log(sayHi('Ryder')) //Hello Ryder
this  的指向。this  ,箭頭函式的 this 會綁定到定義時所在的位置,跟呼叫方法無關,先來看看範例:var name = 'Ryder'
var obj1 = {
	name: 'Jack',
	showName:function(){
		console.log(this.name)
	}
};
var obj2 = {
	name: 'Jack',
	showName:() => {
		console.log(this.name)
	}
};
obj1.showName() // Jack
obj2.showName() // Ryder
上面有提到,箭頭函式的 this 會綁定到定義時所在的位置,這是什麼意思呢?
簡單來說就是: 當該實體、變數在哪裡建立, this 就會指向哪裡,而上面範例的 obj  正是建立在 window 下的,因此 this 是指向 window。
在函式基本章節有提到,傳統函式能夠透過 arguments 這個關鍵字獲得該函式所有參數,而這方法在箭頭函式中無法使用,如範例:
function Fn1(){
	console.log(arguments) // Arguments(2) ['Ryder', 123, ...]
}
Fn1('Ryder', 123)
const Fn2 = () => {
	console.log(arguments) // VM940:2 Uncaught ReferenceError: arguments is not defined
}
Fn2('Ryder', 123)
不過這點可以使用 ES6 新增的其餘參數,來獲得全部參數資料,只需要在參數部分填上 ...arg  之後的 arg  便可獲得全部參數資料。(arg 可自定義名稱
const Fn3 = (...arg) => {
	console.log(arg) //['Ryder', 123]
}
Fn3('Ryder', 123)
上面有提到箭頭含是沒有自己的 this ,因此建構式函式自然無法使用
const TShirt = (color,material,size) => {
	this.color = color
	this.material = material
	this.size = size
}
const BlackTShit = new TShirt('black','棉','L') //TShirt is not a constructor
箭頭函式的 this  是無法使用  call、apply 、 bind 上述綁定 this 功能,箭頭函式的 this 會是固定的。
const obj = {
	name:'Ryder'
}
const Fn1 = () => {
	console.log(this) }
function Fn2(){
	console.log(this)
}
Fn1.call(obj) // Window
Fn2.call(obj) // {name: 'Ryder'}